import { Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { StatusEntity } from '../entity/status.entity';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';

@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
export class StatusService {
  @InjectEntityModel(StatusEntity)
  statusModel: Repository<StatusEntity>;

  //添加默认角色
  async addDefaultStatus() {
    await this.addStatus({ id: 0, name: 'root' });
    await this.addStatus({ id: 1, name: 'user' });
  }

  //添加角色
  private async addStatus(s: StatusEntity) {
    try {
      // 检查是否已经存在相同的记录
      const existingStatus = await this.statusModel.findOneBy({ name: s.name });
      if (existingStatus) {
        console.warn(`角色：${s.name} 已存在 跳过添加`);
        return;
      }
      // 插入数据
      const insertMsg = await this.statusModel.insert(s);
      console.log(`角色：${s.name} 添加成功 ${JSON.stringify(insertMsg)}`);
    } catch (error) {
      // 捕获并记录错误
      console.error(`添加状态失败"${s.name}":`, error);
      throw new Error(`添加状态失败 "${s.name}": ${error.message}`);
    }
  }
}
